package com.github.rxyor.netty.exemple.case2;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 *<p>
 *
 *</p>
 *
 * @author liuyang
 * @date 2020/5/23 周六 16:25:00
 * @since 1.0.0
 */
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    private final static ChannelGroup GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();

        GROUP.forEach(element -> {
            if (channel != element) {
                element.writeAndFlush(String.format("[%s]发送消息:[%s]\n", channel.remoteAddress(), msg));
            } else {
                element.writeAndFlush(String.format("[Self] [%s]\n", msg));
            }
        });
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        GROUP.writeAndFlush(String.format("[Sever][%s] join\n", channel.remoteAddress()));
        GROUP.add(channel);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        GROUP.writeAndFlush(String.format("[Sever][%s] leave\n", channel.remoteAddress()));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(String.format("[%s] online", ctx.channel().remoteAddress()));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(String.format("[%s] offline", ctx.channel().remoteAddress()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
